package com.wk.listener;

import java.util.Arrays;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wk.cache.CacheFacade;
import com.wk.commons.Constants;
import com.wk.util.NetUtil;
import com.wk.util.PropertiesUtil;


/**
 * 删除redis
 * @author chenxiaozhong
 *
 */
public class RedisListener implements ServletContextListener{

	private final static CacheFacade cacheFacade = CacheFacade.getInstance();
	private Logger logger = LoggerFactory.getLogger(RedisListener.class);
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {

		String ipAdds = NetUtil.getLocalIP();
		logger.info("本地IP 为:"+ipAdds);
		if (canDeleteRedis(ipAdds)) {
			logger.info("************关闭服务，清除Redis服务器上的缓存数据 ---开始");
			cacheFacade.delete(Constants.LOGIN_SESSION_KEY);
			logger.info("************关闭服务，清除Redis服务器上的缓存数据 ---结束");
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		String ipAdds = NetUtil.getLocalIP();
		logger.info("本地IP 为:"+ipAdds);
		if (canDeleteRedis(ipAdds)) {
			logger.info("************启动服务前，清除Redis服务器上的缓存数据 ---开始");
			cacheFacade.delete(Constants.LOGIN_SESSION_KEY);
			logger.info("************启动服务前，清除Redis服务器上的缓存数据 ---结束");
		}
	}

	public boolean canDeleteRedis(String ip) {
		if (ip != null && !"".equals(ip)) {
			PropertiesUtil p = new PropertiesUtil("redis.properties");
			String configIp = p.getProperty("redis.ipAddr");
			if (configIp != null && !"".equals(configIp)) {
				String []ips=configIp.split(",");
				if(ips!=null && ips.length>0){
					if(Arrays.asList(ips).contains(ip)){
						return true;
					}
				}
			}
		}
		return false;
	}

}
